<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../lib/ext/resources/css/ext-all-neptune.css"/>
    <link rel="stylesheet" type="text/css" href="../lib/ckeditor/sample.css" />
    <script type="text/javascript" src="../lib/ext/ext-all.js"></script>
    <script type="text/javascript" src="../lib/ckeditor/ckeditor.js"></script>
    <script type="text/javascript" src="../lib/ckeditor/sample.js"></script>
    <script type="text/javascript" src="../lib/ext_ux_ckeditor.js"></script>
    <script type="text/javascript" src="../js/dict_store.js"></script>
    <script type="text/javascript" src="../lib/ext/plugins/clearButton/ClearButton.js" ></script>
    <style type="text/css">
        span.cke_wrapper cke_ltr,table.cke_editor, td.cke_contents, span.cke_skin_kama, span.cke_wrapper, span.cke_browser_webkit{
            height: 100%!important;
        }
    </style>
</head>
<script type="text/javascript">

    var dataForm;
    Ext.require('Ext.tab.*');
    Ext.Loader.setConfig({enabled: true});
    Ext.onReady(function () {
        var i = 0,index_src=0;
        var data = {};
        //var data = {};
        //定义tab
        var tabs = new Ext.widget('tabpanel',{
            colspan : 2,
            autoShow: true
        });

        var tbar = [
            {pressed: true,text: '保  存',handler: doAdd,icon : '../img/book.png'},
            {pressed: true,text: "添加素材",handler: doAddSrc,icon : '../img/add.png'},
            {pressed: true,text: "关  闭",handler: doClose,icon : '../img/close.png'}
        ];
        var rd_folded = new Ext.form.RadioGroup({
            fieldLabel : '是否折叠',
            columns: [100,100],
            items: [{boxLabel: '是', checked: true, name: 'is_folded',inputValue:true},
                {boxLabel: '否', name: 'is_folded',inputValue:false}]
        });




        dataForm  = new Ext.FormPanel({
            autoScroll:true,
            overflowY: 'scroll',
            //renderTo: document.body,
            border: 5,
            style: {
                borderColor: '157fcc',
                borderStyle: 'solid'
            },
            items: [
                {
                    xtype: 'form',
                    layout: {type: 'table',columns:1},
                    defaultType: 'textfield',
                    items : [
                        {name:'type',value:'news',hidden:true},
                        {name:'_id',hidden:true},
                        {fieldLabel : '标题',name:'title',allowBlank: false},
                        {
                            fieldLabel : '日期',
                            name : 'init_date',
                            xtype : 'datefield',
                            editable  : false,
                            format: 'Y/m/d',
                            value : new Date(),
                            plugins: ['clearbutton']
                        },
                        {
                            xtype: 'combobox',
                            fieldLabel: '所属栏目',
                            id : "category",
                            name : 'category',
                            queryMode: 'local',
                            displayField: 'key_name',
                            valueField: 'key_code',
                            allowBlank: false,
                            editable : false,
                            store:  dict_store
                        },
                        {xtype: "filefield",fieldLabel: '素材图片浏览',width:400,name: 'attach_file'},
                        {
                            xtype : "label",
                            text: '(请先点击Browser按钮选择图片后，再点击下方“上传图片”按钮，进行图片上传)',
                            style: {
                                color : 'red'
                            }
                        },
                        tabs
                    ],
                    tbar : tbar
                }
            ]
        });



        //初始化新增协议
        function init_src(){
            if(!data.srcs){
                addSrc();
                return;
            }
            for(i=0;i<data.srcs.length;i++){
                addSrc(data.srcs[i]);
            }
        }

        //新增协议
        function addSrc(data){
            data = data || {};
            if(data && data.title){
                title = data.title;
            }
            else{
                title = '新增素材' + (index_src + 1);
            }
            var image_file_id_id = 'image_file_id_' + index_src;
            var ctl_image_file_id = 'ctl_image_file_id_' + index_src;
            var _panel = new Ext.Panel({
                title : title,
                items : [{
                    name : 'src._id',
                    xtype : 'textfield',
                    hidden : true,
                    value : data._id
                },{
                    name : 'src.title',
                    xtype : 'textfield',
                    width : 400,
                    fieldLabel : '标题',
                    value : data.title
                },

                {
                    fieldLabel: '图片id',
                    xtype : 'textfield',
                    name: 'src.image_url',
                    id : image_file_id_id,
                    readOnly : true,
                    width : 400,
                    value:data.image_url
                },
                Ext.create('Ext.Img', {
                    id : ctl_image_file_id,
                    src: '',
                    height : 150
                }),
                {
                    xtype: "button",
                    text: "上传图片",
                    width: 100,
                    handler: function () {
                        uploadFile(dataForm,image_file_id_id,ctl_image_file_id);
                    }
                },
                {
                    name : 'src.directurl',
                    xtype : 'textfield',
                    fieldLabel : '指向链接',
                    width : 400,
                    value : data.directurl
                },
                {
                    name: 'src.content',
                    labelWidth: 30,
                    xtype :'ckeditor',
                    width : '100%',
                    height : 350
                },
                {xtype : "label",text: '描述'},
                {
                    xtype : 'textareafield',
                    name : 'src.description',
                    fieldLabel : '',
                    width : '100%' ,
                    value : data.description
                }]
            })

            tabs.add(_panel);
            tabs.setActiveTab(_panel);
            var _id = document.getElementsByName('src.content').item(index_src).id;
            CKEDITOR.instances[_id].setData(data.content);
            Ext.getCmp(ctl_image_file_id).setSrc(data.image_url);
            index_src++;
        }

        //保存数据
        function doAdd(){
            var params = dataForm.form.getFieldValues();
            if(!params.title){
                Ext.Msg.alert('消息提示', '标题不得为空!');
                return ;
            }
            var _url = '/wx/srcmgt/add';
            if(params && params._id ){
                _url = '/wx/srcmgt/edit';
            }
            if(params && params.init_date){
                params.init_date = Ext.util.Format.date(params.init_date,'Ymd')
            }
            Ext.Ajax.request({
                url: _url,
                params : params,
                method : 'POST',
                success: function(response, opts) {
                    alert('业务处理成功');
                    parent.refresh();
                    parent.closeWin();
                },
                failure: function(response, opts) {
                    alert('业务处理失败');
                }
            });

        }

        function doClose(){
            parent.closeWin();
        }
        //添加协议
        function doAddSrc(){
            addSrc();
        }

        function init(){
            data = data || {};
            for(var i in data){
                if(dataForm.form.findField(i)){
                    dataForm.form.findField(i).setValue(data[i]);
                }
            }
            if(data && data.init_date){
                dataForm.form.findField('init_date').setValue(Ext.Date.parse(data.init_date,'Ymd'));
            }
            //下拉框的加载
            dict_store.load({params:{parent_code : "wx_src_news"},callback:function(){
                dataForm.form.findField('category').setValue(data.category);
            }});
            init_src();
            tabs.setActiveTab(0);
        }

        var viewport = new Ext.Viewport({
            autoScroll : true,
            layout: 'fit',
            renderTo: 'mypanel',
            items: [dataForm]
        });

        //获取url中的参数，如果传入了参数_id那么进行修改；否则，添加。
        var _urlparams = Ext.urlDecode(document.URL.split("?")[document.URL.split("?").length - 1]);
        if(_urlparams && _urlparams._id){
            Ext.Ajax.request({
                url: '/wx/srcmgt/detail',
                params : {'_id' : _urlparams._id},
                method : 'get',
                success: function(response, opts) {
                    data =  Ext.decode(response.responseText) || {};
                    console.log(data);
                    init();
                },
                failure: function(response, opts) {
                    alert('加载失败......');
                    init();
                }
            });
        }
        else{
            init();
        }

    });


    //处理上传图片
    function uploadFile(_form,image_file_id_id,ctl_image_file_id) {
        var url = "/file/upload";
        if (!_form.getForm().findField("attach_file").getValue()) {
            Ext.Msg.alert('消息提示', '请浏览需要上传的文件!');
            return;
        }
        _form.form.submit({
            url: url,
            waitMsg: '正在提交数据，稍后...',
            success: function (form, action) {
                Ext.getCmp(image_file_id_id).setValue('/_image/' + action.result.file_id);
                Ext.getCmp(ctl_image_file_id).setSrc('/_image/' + action.result.file_id);
                Ext.Msg.alert('消息提示', '上传成功，请按保存继续操作！');
            },
            failure: function (form, action) {
                Ext.Msg.alert('消息提示', '上传失败！');
            }
        });
    }
</script>
<body>
<div id="mypanel" style="width:100%"></div>
</body>
</html>